import Vue from 'vue'
import Vuex from 'vuex'
import router from "../router/index"
import {
  login
} from "@/api"
import persistedState from 'vuex-persistedstate'
Vue.use(Vuex)
import {
  Toast
} from 'vant';
//types
const types = {
  SET_LOCATION: "SET_LOCATION",
  SET_ADDRESS: "SET_ADDRESS",
  SET_USER: "SET_USER",
  SET_TOKEN: "SET_TOKEN",
  SET_CITY: "SET_CITY",
  SET_DISTRICT: "SET_DISTRICT"

}
//state
const state = {
  location: {},
  address: "",
  user: {},
  token: "",
  district: "",
  city: ""
}

//getters
const getters = {
  location: state => state.location,
  address: state => state.address,
  user: state => state.user,
  token: state => state.token,
  district: state => state.district,
  city: state => state.city
}
//mutations
const mutations = {
  [types.SET_LOCATION](state, location) {
    if (location) {
      state.location = location
    } else {
      state.location = null
    }
  },
  [types.SET_ADDRESS](state, address) {
    if (address) {
      state.address = address
    } else {
      state.address = ""
    }
  },
  [types.SET_USER](state, user) {
    if (user) {
      // console.log(user)
      state.user = user
    } else {
      state.user = ""
    }
  },
  [types.SET_TOKEN](state, token) {
    if (token) {
      // console.log(token)

      state.token = token
    } else {
      state.token = ""
    }
  },
  [types.SET_CITY](state, city) {
    if (city) {
      // console.log(token)

      state.city = city
    } else {
      state.city = ""
    }
  },
  [types.SET_DISTRICT](state, district) {
    if (district) {
      // console.log(token)

      state.district = district
    } else {
      state.district = ""
    }
  }
}
//actions
const actions = {
  setLocation: ({
    commit
  }, location) => {
    // console.log(location)

    commit(types.SET_LOCATION, location)
  },
  setAddress: ({
    commit
  }, address) => {
    console.log(address)

    commit(types.SET_ADDRESS, address)
  },
  login: ({
    commit
  }, user) => {
    login(user).then(res => {
      console.log(res, "userInfo")
      if (res.data.code === 10000) {
        Toast("登录成功")
        setTimeout(() => {
          router.push('/')
        }, 1500)
        commit(types.SET_USER, res.data.data)
        commit(types.SET_TOKEN, res.data.msg)
      }
    })
  },
  eliminate({
    commit
  }) {
    commit(types.SET_TOKEN, "")
    commit(types.SET_USER,"")
    setTimeout(() => {
      router.push('/me')
    }, 1500)
    Toast("已退出")
  }

}
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  plugins: [persistedState({})]
})